package solution._0020._0025;

import common.ListNode;

/**
 * Created by chen_snow
 * Date: 2021/5/17 22:45
 * Description: K 个一组翻转链表
 */
public class Solution {

    public static void main(String[] args) {
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(5);

        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;

        reverseKGroup(node1, 2);

    }

    public static ListNode reverseKGroup(ListNode head, int k) {

        if (k == 1) {
            return head;
        }

        ListNode result = new ListNode(0);
        result.next = head;
        ListNode next = result;


        ListNode first = next.next;
        ListNode last = next;

        while (next != null) {
            for (int i = 0; i < k; i++) {
                if (last.next != null) {
                    last = last.next;
                } else {
                    return result.next;
                }
            }

            reverse(first, last);

            next.next = last;
            next = first;
            last = first;
            first = next.next;

        }


        return result.next;
    }

    /**
     * 翻转 head 到 tail 之间的节点
     * @param head
     * @param tail
     */
    public static void reverse(ListNode head, ListNode tail) {
        ListNode last = tail.next;

        ListNode next = head.next;
        ListNode before = head;

        while (before != tail) {
            ListNode tmp = next.next;
            next.next = before;
            before = next;
            next = tmp;
        }

        head.next = last;

    }

}
